const fs = require("fs");
const router = require('koa-router')();
module.exports = (app) => {
    const controller = querydir("./src/controller");
    const api = "/api"
    controller.forEach(element => {
        let contorFc = require("../controller" + element);
        Object.keys(contorFc).forEach(key => {
            let data = contorFc[key];
            let [name, method, params] = data.name.split("_");
            var paramsAll = "";
            if (params) {
                paramsAll = "/:" + params
            }
            router[method || "post"](api + element + "/" + name + paramsAll, data)
            console.log("请求方式：" + (method || "post") + "\n可以请求路径：" + api + element + "/" + name + paramsAll)
        })
    });
    const path = require('path');
    app.on("error", (err, ctx) => {
        if (err.code != 'ECONNRESET') {
            console.log(err);
        }
    })
    app.use(router.routes())
    app.use(router.allowedMethods());
}

//获取路径
function querydir(path) {
    var arr = [];
    let list = fs.readdirSync(path);
    list.forEach(name => {
        let dir = path + '/' + name;
        let isFile = fs.statSync(dir);
        name = name.replace(/\.js$/g, "");
        name = "/" + name
        if (name == "/index") { name = "" }
        if (isFile && isFile.isDirectory()) {
            var data = querydir(dir)
            data.forEach(item => arr.push(name + item))
        } else {
            arr.push(name)
        }
    })
    return arr;
}